package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    /**
     * 登录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult AdUserLogin(AdUserDto dto) {

        //校验参数是否存在
        if (StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //获取数据库中的user对象
        LambdaQueryWrapper<AdUser> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(AdUser::getName, dto.getName());
        AdUser adUser = getOne(wrapper);

        //判断账号是否存在
        if (null == adUser) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "账号不存在");
        }

        //将参数密码经行加密判断
        String word = dto.getPassword() + adUser.getSalt();
        String wordSalt = DigestUtils.md5DigestAsHex(word.getBytes());

        //判断密码是否正确
        if (wordSalt.equals(adUser.getPassword())) {

            //正确返回token
            String token = AppJwtUtil.getToken(adUser.getId());
            Map<String, Object> map = new HashMap<>();
            adUser.setPassword("");
            adUser.setSalt("");
            map.put("token", token);
            map.put("user", adUser);
            return ResponseResult.okResult(map);
        } else {

            //错误 返回错误参数
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
    }
}
